package com.yhw.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yhw.srb.core.listener.ExcelDictDTOListener;
import com.yhw.srb.core.pojo.entity.Dict;
import com.yhw.srb.core.mapper.DictMapper;
import com.yhw.srb.core.pojo.entity.dto.ExcelDictDTO;
import com.yhw.srb.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author yhw
 * @since 2022-08-29
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = {Exception.class})  // 事务处理 防止导入一半出问题 再次导入困难   要么一起成功 要么一起失败
    @Override
    public void importData(InputStream inputStream) {
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭    从inputStream中一行一行的读取数据
        EasyExcel.read(inputStream, ExcelDictDTO.class,new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("importData 完成");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);

        List<ExcelDictDTO> excelDictDTOList = new ArrayList<>(dictList.size());

        for (Dict dict:dictList) {
            ExcelDictDTO dictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict,dictDTO);
            excelDictDTOList.add(dictDTO);
        }

        return excelDictDTOList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        List<Dict> dictList = null;

        try {   // 加 try-catch  是想  不要因为redis那边出问题 就抛异常 停止业务执行
                // 是想即使redis那边出问题 我们也要正常的执行后面的流程，使业务可以正常的运行
            dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (dictList != null) {
                log.info("从redis中取值");
                return dictList;
            }
        }catch (Exception e){
            //此处不抛出异常，继续执行后面的代码
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));
        }

        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId,parentId);
        dictList = baseMapper.selectList(queryWrapper);
        for (Dict dict:dictList) {
            boolean b = hasChildren(dict.getId());  //判断是否有子节点
            if (b){
                dict.setHasChildren(b);
            }
        }

        try {
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
            log.info("数据存入redis");
        }catch (Exception e){
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));//此处不抛出异常，继续执行后面的代码
        }

        return dictList;
    }

    /**
     * 判断该节点是否有子节点
     */
    public boolean hasChildren(Long id){

        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getParentId,id);
        Integer integer = baseMapper.selectCount(queryWrapper);
        if (integer > 0) {
            return true;
        }

        return false;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {

        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dict::getDictCode,dictCode);
        Dict parentDict = baseMapper.selectOne(queryWrapper);

        if(parentDict == null) {
            return "";
        }


        LambdaQueryWrapper<Dict> newqueryWrapper = new LambdaQueryWrapper<>();
        newqueryWrapper.eq(Dict::getParentId,parentDict.getId())
                     .eq(Dict::getValue,value);
        Dict dict = baseMapper.selectOne(newqueryWrapper);

        if(dict == null) {
            return "";
        }

        return dict.getName();
    }
}
